package services

import (
	"encoding/json"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/jinzhu/gorm"
	"go_motor_catalog/dao"
	"go_motor_catalog/util"
	"os"
	"strings"
)

const getCodeUrl = "https://www.kawasaki-onlinetechinfo.net/ajaxMarketingCodeList?nickname=NICKNAME&category_num=1&first_referrer=https%3A%2F%2Fwww.kawasaki-motors.com%2F"

const getYearUrl = "https://www.kawasaki-onlinetechinfo.net/ajaxFindListModelYear?nickname=NICKNAME&model=CODE&category_num=1&first_referrer=https://www.kawasaki-motors.com/"

const getManualUrl = "https://www.kawasaki-onlinetechinfo.net/manualsSearch?category_num=1&first_referrer=https://www.kawasaki-motors.com/&nickname=NICKNAME&model=CODE&parts=0&fr_year=YEAR&to_year=YEAR"

type KawasakiOm struct {
}

type KawasakiRes struct {
	ModelName string
	ModelYear string
	Catalog   string
}

func NewKawasakiOm() *KawasakiOm {
	return &KawasakiOm{}
}

func (k *KawasakiOm) getModel() []string {
	res := make([]string, 0)
	file, err := os.Open("E://kawasaki.html")
	if err != nil {
		fmt.Println("读取html失败", err)
		return nil
	}
	dom, err := goquery.NewDocumentFromReader(file)
	if err != nil {
		fmt.Println("解析html失败", err)
		return nil
	}
	table := dom.Find("table")
	tr := table.Find("tr")
	selector := tr.Find("select")
	selector = selector.First().Find("option")
	options := selector.Nodes
	for i := range options {
		option := options[i]
		attrs := option.Attr
		for a := range attrs {
			if attrs[a].Key == "value" && attrs[a].Val == "0" {
				break
			} else {
				model := attrs[a].Val
				model = strings.ReplaceAll(model, "@", "")
				res = append(res, model)
			}
		}
	}
	return res
}

func (k *KawasakiOm) getCode(nickName string) string {
	nickName = strings.ReplaceAll(nickName, " ", "%20")
	url := strings.ReplaceAll(getCodeUrl, "NICKNAME", nickName)
	resty := util.NewHttpUtil().PostResty(url, nil)
	jsonBody := make([]map[string]interface{}, 0)
	err := json.Unmarshal(resty.Body(), &jsonBody)
	if err != nil {
		fmt.Println("获取model code失败", err)
		return ""
	}
	code := fmt.Sprintf("%v", jsonBody[1]["value"])
	return code
}

func (k *KawasakiOm) getYear(nickName string, code string) []string {
	nickName = strings.ReplaceAll(nickName, " ", "%20")
	res := make([]string, 0)
	var url string
	url = strings.ReplaceAll(getYearUrl, "NICKNAME", nickName)
	url = strings.ReplaceAll(url, "CODE", code)
	resty := util.NewHttpUtil().PostResty(url, nil)
	jsonBody := make([]map[string]interface{}, 0)
	json.Unmarshal(resty.Body(), &jsonBody)
	for i := range jsonBody {
		bean := jsonBody[i]
		year := fmt.Sprintf("%v", bean["value"])
		if year == "0" {
			continue
		}
		res = append(res, year)
	}
	return res
}

func (k *KawasakiOm) getManual(nickName string, code string, year string) string {
	nickName = strings.ReplaceAll(nickName, " ", "%20")
	var url string
	url = strings.ReplaceAll(getManualUrl, "NICKNAME", nickName)
	url = strings.ReplaceAll(url, "CODE", code)
	url = strings.ReplaceAll(url, "YEAR", year)
	resty := util.NewHttpUtil().Post(url)
	dom, err := goquery.NewDocumentFromResponse(resty)
	if err != nil {
		return ""
	}
	a := dom.Find("#accordion").Find("li").Find("span").First().Find("a").First()
	val, exists := a.Attr("href")
	if !exists {
		return ""
	}
	return val
}

func (k *KawasakiOm) CrawData(db *gorm.DB) []*KawasakiRes {
	res := make([]*KawasakiRes, 0)
	omDao := dao.NewManualModelOmDao(db)
	catalogDao := dao.NewManualCatalogOmDao(db)
	models := k.getModel()
	for i := range models {
		model := models[i]
		code := k.getCode(model)
		years := k.getYear(model, code)
		for y := range years {
			year := years[y]
			manual := k.getManual(model, code, year)
			if manual == "" {
				continue
			}
			res = append(res, &KawasakiRes{
				ModelName: model,
				ModelYear: year,
				Catalog:   manual,
			})
			modelBean := &dao.ManualModelOm{
				ModelName:       model,
				ModelNameDetail: code,
				ModelYear:       year,
				BrandId:         3,
			}
			catalogBean := &dao.ManualCatalogOm{
				CatalogSpareUrl: manual,
				CatalogDesc:     "hardBook",
			}
			omDao.CreateManualModelOm(modelBean)
			if modelBean.Id == 0 {
				continue
			}
			catalogBean.ModelId = modelBean.Id
			catalogDao.CreateManualCatalogOm(catalogBean)
			fmt.Println(model, "-", year, "-successfull")
		}
	}
	return res
}
